import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, message, Descriptions, Modal, Divider, Space } from 'antd';
import { UserOutlined, MailOutlined, PhoneOutlined, EditOutlined, LockOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';

import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import LogoutButton from '@/components/LogoutButton';
import type { UserProfile, UserProfileRequest, UserPasswordChangeRequest } from '@/services/generated';

const Profile: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState<UserProfile | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [editForm] = Form.useForm();
  const [passwordForm] = Form.useForm();

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.users.usersProfileRetrieve();
      setUserInfo(response.data);
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      message.error('获取用户信息失败');
    } finally {
      setLoading(false);
    }
  };

  // 更新个人信息
  const handleUpdateProfile = async (values: UserProfileRequest) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.users.usersUpdateProfileUpdate({
        userProfileRequest: values
      });
      setUserInfo(response.data);
      message.success('个人信息更新成功');
      setEditModalVisible(false);
    } catch (error: any) {
      console.error('更新失败:', error);
      message.error(error?.response?.data?.message || '更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handleChangePassword = async (values: UserPasswordChangeRequest) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.users.usersChangePasswordCreate({
        userPasswordChangeRequest: values
      });
      message.success('密码修改成功');
      setPasswordModalVisible(false);
      passwordForm.resetFields();
    } catch (error: any) {
      console.error('密码修改失败:', error);
      const errorData = error?.response?.data;
      if (errorData?.errors) {
        Object.keys(errorData.errors).forEach(field => {
          const fieldErrors = errorData.errors[field];
          if (Array.isArray(fieldErrors)) {
            message.error(`${field}: ${fieldErrors.join(', ')}`);
          }
        });
      } else {
        message.error(errorData?.message || '密码修改失败');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserInfo();
  }, []);

  useEffect(() => {
    if (editModalVisible && userInfo) {
      editForm.setFieldsValue({
        email: userInfo.email,
        real_name: userInfo.real_name,
        phone: userInfo.phone,
      });
    }
  }, [editModalVisible, userInfo, editForm]);

  return (
    <PageContainer title="个人信息">
      <Card loading={loading}>
        <Descriptions
          title="基本信息"
          extra={
            <Button 
              type="primary" 
              icon={<EditOutlined />} 
              onClick={() => setEditModalVisible(true)}
            >
              编辑信息
            </Button>
          }
          column={2}
        >
          <Descriptions.Item label="用户名">{userInfo?.username}</Descriptions.Item>
          <Descriptions.Item label="邮箱">{userInfo?.email}</Descriptions.Item>
          <Descriptions.Item label="真实姓名">{userInfo?.real_name || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="手机号">{userInfo?.phone || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="状态">{userInfo?.status}</Descriptions.Item>
          <Descriptions.Item label="注册时间">
            {userInfo?.created_at ? new Date(userInfo.created_at).toLocaleString('zh-CN') : '未记录'}
          </Descriptions.Item>
          <Descriptions.Item label="最后登录">
            {userInfo?.last_login_at ? new Date(userInfo.last_login_at).toLocaleString('zh-CN') : '未记录'}
          </Descriptions.Item>
        </Descriptions>

        <Divider />

        <Space>
          <Button
            type="default"
            icon={<LockOutlined />}
            onClick={() => setPasswordModalVisible(true)}
          >
            修改密码
          </Button>

          <LogoutButton />
        </Space>
      </Card>

      {/* 编辑信息Modal */}
      <Modal
        title="编辑个人信息"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleUpdateProfile}
        >
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入有效的邮箱地址!' },
            ]}
          >
            <Input prefix={<MailOutlined />} placeholder="邮箱地址" />
          </Form.Item>

          <Form.Item
            name="real_name"
            label="真实姓名"
          >
            <Input prefix={<UserOutlined />} placeholder="真实姓名" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
          >
            <Input prefix={<PhoneOutlined />} placeholder="手机号" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} style={{ marginRight: 8 }}>
              保存
            </Button>
            <Button onClick={() => setEditModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码Modal */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        footer={null}
        width={400}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handleChangePassword}
        >
          <Form.Item
            name="old_password"
            label="原密码"
            rules={[{ required: true, message: '请输入原密码!' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="原密码" />
          </Form.Item>

          <Form.Item
            name="new_password"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码!' },
              { min: 6, message: '密码至少6个字符!' },
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="新密码" />
          </Form.Item>

          <Form.Item
            name="new_password_confirm"
            label="确认新密码"
            dependencies={['new_password']}
            rules={[
              { required: true, message: '请确认新密码!' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('new_password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="确认新密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} style={{ marginRight: 8 }}>
              修改密码
            </Button>
            <Button onClick={() => setPasswordModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Profile;
